from datetime import datetime
import time as time_module
from sqlalchemy import select, func
from sqlalchemy.ext.asyncio import AsyncSession
from module_admin.entity.do.gamerecord_do import BaGameRecord
from module_admin.entity.do.machine_do import BaMachine
from module_admin.entity.vo.gamerecord_vo import GameRecordPageQueryModel
from utils.page_util import PageUtil
from utils.log_util import logger

class GameRecordDao:
    """
    游戏记录表数据库操作层
    """

    @classmethod
    async def get_list(
        cls, db: AsyncSession, query_object: GameRecordPageQueryModel, data_scope_sql: str, is_page: bool = False
    ):
        """
        根据查询参数获取机台列表信息

        :param db: orm对象
        :param query_object: 查询参数对象
        :param data_scope_sql: 数据权限对应的查询sql语句
        :param is_page: 是否开启分页
        :return: 用户列表信息对象
        """
        
        query = (
            select(BaGameRecord, BaMachine.machine_id)
            .join(BaMachine, BaGameRecord.m_id == BaMachine.id)  # 连表条件
            .where(
                BaGameRecord.m_id == query_object.m_id if query_object.m_id else True,
                BaGameRecord.create_time.between(
                    int(time_module.mktime(datetime.strptime(query_object.begin_time, '%Y-%m-%d').timetuple())),
                    int(time_module.mktime(datetime.strptime(query_object.end_time, '%Y-%m-%d').timetuple())) + 86399
                )
                if query_object.begin_time and query_object.end_time
                else True
            )
            .order_by(BaGameRecord.create_time.desc())
            .distinct()
        )
        list_data = await PageUtil.paginate(db, query, query_object.page_num, query_object.page_size, is_page)
        
        # 处理返回数据
        processed_data = []
        for record in list_data.rows:
            # record是一个包含BaGameRecord和machine_id的元组
            row_record = record[0] if isinstance(record[0], dict) else record[0].__dict__
            machine_id = record[1]
            
            # 删除SQLAlchemy的内部状态
            if '_sa_instance_state' in row_record:
                del row_record['_sa_instance_state']
            
            # 添加machine_id到记录中
            row_record['machine_id'] = machine_id
            processed_data.append(row_record)
        list_data.rows = processed_data

        # logger.info(f'query_object: {query_object}')
        # compiled_query = query.compile(compile_kwargs={"literal_binds": True})
        # logger.info(f'compiled_query: {str(compiled_query)}')
        
        return list_data
    
    @classmethod
    async def add_dao(cls, db: AsyncSession, addModel: GameRecordPageQueryModel):
        """
        新增数据库操作

        :param db: orm对象
        :param addModel: 新增对象
        :return:
        """
        db_result = BaGameRecord(**addModel.model_dump())
        db.add(db_result)
        await db.flush()

        return db_result